<template>
  <div class="uploadImg flex-col" ref="upload">
    <div class="content flex-row flex-1">
      <div class="left flex-center" @click="handleSelectFile">
        <i v-if="!img.previewUrl" style="font-size: 50px" class="el-icon-plus"/>
        <img class="previewImg" v-else :src="img.previewUrl" alt="">
      </div>
      <div class="right flex-col flex-1">
        <vs-button size="mini">选择本地图片</vs-button>
        <vs-button size="mini" disabled>选择网络图片</vs-button>
        <vs-button size="mini" :disabled="!img.previewUrl">预览</vs-button>
        <vs-button size="mini" :disabled="img.isFinish || !img.file" @click="fetchUpload">上传</vs-button>
      </div>
    </div>
    <input @change="handleUpload" ref="file" type="file" hidden>
  </div>
</template>

<script>
import {uploadFile} from "@/api/table/upload"

export default {
  name: "UploadImg",
  props:{
    uploadType:{
      default: 0,  // 0所有 1图片 2md 3txt  name.splice(".")字符串
    }
  },
  data: () => ({
    img: {
      previewUrl: "",
      isFinish: false,
      file: null,
      fileName: ""
    }
  }),
  methods:{
    fetchUpload() {
      const loading = this.$vs.loading({
        text: 'Loading...',
        target: this.$refs.upload
      })
      uploadFile(this.img.file).then(ret=>{
        loading.close()
        if(ret.code===0){
          this.img.isFinish = true
          this.$emit("success", {url: ret.url, name: this.img.fileName})
        }
      })
    },
    handleSelectFile() {
      this.$refs.file.click()
    },
    handleUpload(e) {
      let files = e.target.files
      let blobUrl = URL.createObjectURL(files[0])
      this.img.fileName = files[0].name
      this.img.isFinish = false
      this.img.file = files[0]
      this.img.previewUrl = blobUrl
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/css/var";
.uploadImg{
  //border-radius: 5px;
  background-color: rgba(255,255,255 ,0.9);
  //width: 400px;
  padding: $pn;
  .title{
    text-align: center;
    font-weight: 600;
    font-size: 20px;
    line-height: 2;
  }
  .left{
    width: 200px;
    height: 200px;
    border: 1px dashed red;
    cursor: pointer;
  }
}

.previewImg{
  width: 100%;
  max-height: 100%;
}
</style>
